<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, watch, nextTick, PropType } from 'vue'
import useSchema from './hooks/useSchema'
import { AllSchemas, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { ElInput, ElButton, ElIcon, FormRules, ElMessage, ElMessageBox, ElTag } from 'element-plus'
import { CurdData } from '@/api/transactionCurrency/types'
import { ref } from 'vue'
import { FieldEnum } from '@/api/transactionCurrency/types'
import { getFieldEnumApi } from '@/api/transactionCurrency'
import { SchemaConfig } from '@/api/global/types'

defineOptions({
  name: 'WarehousetSave'
})

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})
const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const fieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
const getSelectEnum = async () => {
  getFieldEnumApi({ field: 'all' })
    .then((res) => {
      fieldEnum.value = res.data.list
      const schemaConfig: SchemaConfig = {
        fieldEnum: fieldEnum.value
      }
      const { crudSchemas } = useSchema(schemaConfig)
      const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

      // 合并新的数据，确保不改变原有数据的类型
      allSchemas.value = {
        formSchema: newSchemas.formSchema || []
      }
    })
    .catch((error) => {
      console.error('API call failed', error)
    })
}

getSelectEnum()

const rules: FormRules = reactive({})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()

    return formData
  }
}

watch(
  () => props.currentRow,
  async (currentRow) => {
    if (!currentRow) return

    await nextTick()
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
